/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.yongw.MouseMove;

import static cn.yongw.MouseMove.ReceiveDataUtil.receiveData;
import java.io.IOException;
import java.io.InputStream;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javafx.scene.control.TextArea;
/**
 *蓝牙服务器
 * @author 张永伟
 */
public class BluetoothJavaServer extends JavaServer{
    private StreamConnectionNotifier mStreamConnectionNotifier = null;
    private StreamConnection mStreamConnection = null;
    private TextArea ta;   
    Format format;    
    InputStream is;
    boolean isRunning = true;
    /**
     * @param ta 展示通知的窗口
     */   
    public BluetoothJavaServer(TextArea ta) throws IOException{
        this.ta = ta;
        format = new SimpleDateFormat("YYYY年yy月dd日HH:mm:ss.SSS");   
        mStreamConnectionNotifier=(StreamConnectionNotifier) Connector
                        .open("btspp://localhost:0000110100001000800000805F9B34FB;name=RemoteBluetoot"); 
        System.out.println("server start listening………");
        Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 无线鼠标蓝牙电脑端已启动,等待手机端连接\n"));
        isRunning=true;
    }
    @Override
    public void run() {
        try{            
            while(isRunning){
                mStreamConnection = mStreamConnectionNotifier.acceptAndOpen();
                System.out.println("client connected, start receive data");
                Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 连接成功,可以开始操作\n"));
                is = mStreamConnection.openInputStream();                
                receiveData(is, ta); //开始接受数据                
                System.out.println("finish receive, start again");
                Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 连接断开,等待重新连接\n"));
                is.close();
                mStreamConnection.close();
            }
        } catch (IOException ex) {
          //  ex.printStackTrace();
           // System.out.println("bluetooth closeed");
        }
    }
    /**
     * 关闭服务器
     */
    public void closeServer(){
        isRunning=false;
        try {
            if(mStreamConnection!=null)
                mStreamConnection.close();
            if(is!=null)
                is.close();            
            mStreamConnectionNotifier.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
